package com.example.cadmin.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.cadmin.entity.Archives;
import com.example.cadmin.entity.ElectronArchives;
import com.example.cadmin.entity.SysParamset;
import com.example.cadmin.mapper.SysParamsetMapper;
import com.example.cadmin.service.ElectronArchivesService;
import com.example.cadmin.service.SysParamsetService;
import com.example.cadmin.utils.DateFormat;
import com.example.cadmin.utils.PDF.mergePDF;
import com.example.cadmin.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.ansj.domain.Result;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 电子档案 前端控制器
 * </p>
 *
 * @author zzsoft
 * @since 2024-04-29
 */
@Slf4j
@RestController
@RequestMapping("/electron/archives")
public class ElectronArchivesController {

    @Resource
    public ElectronArchivesService electronArchivesService;
    @Resource
    public SysParamsetMapper sysParamsetMapper;
    @Value("${SavePath.nginxPath}")
    private String nginxPath;

    /**
     * pdf 表格页面
     */
    @GetMapping("/table")
    public ModelAndView pdfTable(@RequestParam(value = "archivesId") String archivesId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("FileManage/electronArchivesTable");
        modelAndView.addObject("archivesId", archivesId);
        return modelAndView;
    }

    /**
     * pdf合并表格
     */
    @GetMapping("/table/list")
    public Map<String, Object> pdfList(@RequestParam(value = "archivesId") String archivesId,
                                       @RequestParam(value = "page") int page,
                                       @RequestParam(value = "limit") int limit) {
        return electronArchivesService.pdfList(archivesId, limit, page);
    }

    /**
     * 删除电子档案
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public ResponseModel deleteElectron(@PathVariable("id") String id) {
        return electronArchivesService.deleteElectron(id);
    }


    /**
     * 合并电子档案文件
     */
    @PostMapping("/upload/electron/file")
    @ResponseBody
    public Map<String, Object> uploadImg(@RequestPart("file") MultipartFile file) {
        Map<String, Object> resMap = new HashMap<>();
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //为了避免发生图片替换，这里使用了文件名重新生成
        fileName = UUID.randomUUID() + suffixName;
        //拼接前缀路径
        LocalDateTime localDateTime = LocalDateTime.now();
        String middlePath = localDateTime.getYear() + File.separator + localDateTime.getMonthValue();
        SysParamset sysParamset = sysParamsetMapper.selectById(31);
        String basePathJoin = sysParamset.getParamValue() + File.separator + middlePath;
        if (!FileUtil.exist(basePathJoin)) {
            FileUtil.mkdir(basePathJoin);
        }
        try {
            File savePath = new File(basePathJoin + File.separator + fileName);
            //将图片保存到文件夹里
            file.transferTo(savePath);
            //返回文件的路径
            resMap.put("msgName", "图片保存成功");
            resMap.put("savePath", savePath);
            resMap.put("code", 0);
            resMap.put("fileName", file.getOriginalFilename());
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            resMap.put("code", 1);
            return resMap;
        }
    }

    /**
     * 合并档案
     */
    @PostMapping("/merge/pdf")
    @ResponseBody
    public ResponseModel mergePDF(@RequestBody JSONObject data) throws IOException {
        if (StrUtil.isEmpty(data.getStr("archivesId")) || StrUtil.isEmpty(data.getStr("savePath"))
                || StrUtil.isEmpty(data.getStr("lineID"))) {
            return ResponseModel.fail("缺少参数");
        }
        ElectronArchives electronArchives = electronArchivesService.getById(data.getInt("lineID"));
        List<String> mergeFileList = new ArrayList<>();
        mergeFileList.add(electronArchives.getSavePath());
        mergeFileList.add(data.getStr("savePath"));
        LocalDateTime localDateTime = LocalDateTime.now();
        String middlePath = localDateTime.getYear() + File.separator + localDateTime.getMonthValue();
        SysParamset sysParamset = sysParamsetMapper.selectById(31);
        String basePathJoin = sysParamset.getParamValue() + File.separator + middlePath;
        if (!FileUtil.exist(basePathJoin)) {
            FileUtil.mkdir(basePathJoin);
        }
        String fileName = UUID.randomUUID() + ".pdf";
        File savePath = new File(basePathJoin + File.separator + fileName);
        //合并pdf
        boolean mergeStatus = mergePDF.mergePdfFiles(mergeFileList, savePath.getAbsolutePath());

        String nginx = nginxPath + middlePath + File.separator + fileName;
        // 读取PDF
        PDDocument document = PDDocument.load(savePath);
        // 创建PDFTextStripper对象
        PDFTextStripper pdfStripper = new PDFTextStripper();
        // 提取文本
        String text = pdfStripper.getText(document);
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(text);
        String str1 = m.replaceAll("");
        //只关注这些词性的词
        Set<String> name = new HashSet<String>() {{
            add("n");
            add("nr");
            add("nr1");
            add("nr2");
            add("nrj");
            add("nrf");
        }};
        Set<String> placeName = new HashSet<String>() {{
            add("ns");
            add("nsf");
            add("nt");
            add("nz");
            add("f");
        }};
        Set<String> number = new HashSet<String>() {{
            add("m");
        }};
        Set<String> time = new HashSet<String>() {{
            add("t");
        }};
        Result result = ToAnalysis.parse(str1);
        List<Term> terms = result.getTerms(); //拿到terms
//            StringBuilder  documentName = new StringBuilder();
        HashSet<String> documentName = new HashSet<>();
        HashSet<String> documentPlaceName = new HashSet<>();
        HashSet<String> documentNumber = new HashSet<>();
        HashSet<String> documentTime = new HashSet<>();
        for (int i = 0; i < terms.size(); i++) {
            String word = terms.get(i).getName(); //拿到词
            String natureStr = terms.get(i).getNatureStr(); //拿到词性
            if (name.contains(natureStr)) {
                documentName.add(word);
            } else if (placeName.contains(natureStr)) {
                documentPlaceName.add(word);
            } else if (number.contains(natureStr)) {
                documentNumber.add(word);
            } else if (time.contains(natureStr)) {
                documentTime.add(word);
            }
        }
        if (mergeStatus) {
            //文件名称合并处理
            File file1 = FileUtil.file(electronArchives.getUploadFileName());
            File file2 = FileUtil.file(data.getStr("fileName"));
            String name1 = FileNameUtil.mainName(file1);
            String name2 = FileNameUtil.mainName(file2);
            String mergeName = name1 + "-" + name2 + ".pdf";
            UpdateWrapper<ElectronArchives> electronArchivesUpdateWrapper = new UpdateWrapper<ElectronArchives>().eq("id", data.getInt("lineID"))
                    .set("document_name", documentName.toString()).set("document_placeName", documentPlaceName.toString())
                    .set("document_number", documentNumber.toString()).set("document_time", documentTime.toString()).set("electron_file", nginx)
                    .set("save_path",savePath.getAbsolutePath()).set("update_time",DateFormat.getTime()).set("upload_file_name",mergeName);
            electronArchivesService.update(electronArchivesUpdateWrapper);
            return ResponseModel.success("合并成功");
        } else {

            return ResponseModel.fail("合并失败");

        }
    }
}
